package com.ny.controller;
import com.ny.entity.Device1;
import com.ny.entity.Result;
import com.ny.service.DeviceService1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/devices")
public class DeviceController1 {
    @Autowired
    private DeviceService1 deviceService1;

    // GET请求查询所有设备
    // http://localhost:8083/devices
    @GetMapping
    public List<Device1> getAllDevices() {
        return deviceService1.getAllDevices();
    }
    //根据设备名称查询设备数据
    // http://localhost:8083/devices/findDeviceByname?name=设备名称
    @GetMapping("/findDeviceByname")
    public List<Device1> findDeviceByname(String name) {
        return deviceService1.findDeviceByname(name);
    }

    // POST请求添加设备数据
    //POST http://localhost:8083/devices/addDevice
    //Content-Type: application/json
    //
    //{
    //    "deviceNo": "设备编号",
    //    "name": "设备名称",
    //    "type": "设备类型",
    //    "status": "设备状态",
    //    "factory": "生产厂家"
    //}
    @PostMapping("/addDevice")
    public Result addDevice(@RequestBody Device1 device) {
        // 1. 检查设备编号是否已存在
        Optional<Device1> existingDevice = deviceService1.findByDeviceNo(device.getDeviceNo());
        if (existingDevice.isPresent()) {
            return Result.error("设备编号已存在");
        }
        // 调用服务层进行添加
        return deviceService1.addDevice(device);
    }
    
    //根据设备deviceNo修改设备信息
    //PUT http://localhost:8083/devices/updateDeviceByDeviceNo/{deviceNo}
    //Content-Type: application/json
    //
    //{
    //    "deviceNo": "设备编号",
    //    "name": "设备名称",
    //    "type": "设备类型",
    //    "status": "设备状态",
    //    "factory": "生产厂家"
    //}
    @PutMapping("/updateDeviceByDeviceNo/{deviceNo}")
    public Result updateDeviceByDeviceNo(@PathVariable String deviceNo, @RequestBody Device1 device) {
        return deviceService1.updateDeviceByDeviceNo(deviceNo, device);
    }
    
    //根据设备ID删除设备
    //DELETE http://localhost:8083/devices/deleteDevice/{id}
    @DeleteMapping("/deleteDevice/{id}")
    public Result deleteDevice(@PathVariable String id) {
        return deviceService1.deleteDeviceById(id);
    }
    
    //根据设备名称模糊查询设备数据
    //GET http://localhost:8083/devices/findDevicesByNameContaining?name=厨
    @GetMapping("/findDevicesByNameContaining")
    public List<Device1> findDevicesByNameContaining(@RequestParam String name) {
        return deviceService1.findDevicesByNameContaining(name);
    }

}